package com.mars.service;

import com.google.common.base.Preconditions;
import com.mars.common.RequestHolder;
import com.mars.dao.SysDeptMapper;
import com.mars.dao.SysUserMapper;
import com.mars.exception.ParamException;
import com.mars.param.DeptParam;
import com.mars.pojo.SysDept;
import com.mars.util.BeanValidator;
import com.mars.util.IpUtil;
import com.mars.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author MARS
 * @date 2017/12/28
 */
@Service
public class SysDeptService {

    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    public void save(DeptParam param){
        // 字段验证
        BeanValidator.check(param);
        // 判断部门是否重复
        if(checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept dept = SysDept.builder().name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();

        dept.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        dept.setOperator(RequestHolder.getCurrentUser().getUsername());
        dept.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        dept.setOperateTime(new Date());
        sysDeptMapper.insertSelective(dept);

        // 记录日志
        sysLogService.saveDeptLog(null,dept);
    }

    /**
     * 判断部门是否重复
     */
    private boolean checkExist(Integer parentId,String deptName,Integer deptId){
        return sysDeptMapper.countByNameAndParentId(parentId,deptName,deptId) > 0 ;
    }

    /**
     * 获取部门级别
     */
    private String getLevel(Integer deptId){
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (dept == null) {
            return null;
        }
        return dept.getLevel();
    }

    /**
     * 更新部门
     * @param param
     */
    public void update(DeptParam param){
        // 字段验证
        BeanValidator.check(param);
        // 判断部门是否重复
        if(checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamException("同一层级下存在相同名称的部门");
        }

        // 验证一下更新部门是否存在
        SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的部门不存在");

        //更新后的部门
        SysDept after = SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();

        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());

        updateWithChild(before,after);
        // 记录日志
        sysLogService.saveDeptLog(before,after);
    }

    /**
     * 事物控制，要么都更新成功，要么更新失败
     * @param before
     * @param after
     */
    @Transactional(rollbackFor = Exception.class)
    private void updateWithChild(SysDept before,SysDept after) {
        // 是否更新子部门
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        // 如果两个level不一致，需要做子部门的更新
        if ( !after.getLevel().equals(before.getLevel())) {
            List<SysDept> deptList = sysDeptMapper.getChildDeptListByLevel(before.getLevel()+"."+before.getId());
            if (CollectionUtils.isNotEmpty(deptList)) {
                for (SysDept sysDept : deptList){
                    String level = sysDept.getLevel();
                    if(level.indexOf(oldLevelPrefix) == 0 ) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        sysDept.setLevel(level);
                    }
                }
                //批量更新level
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    // 删除部门
    public void delete(int deptId) {
        // 删除前，先判断该部门是否存在
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        // 不存在给出提示
        Preconditions.checkNotNull(dept,"待删除的部门不存在，无法删除");

        // 存在，查看是否存在子部门和用户
        if (sysDeptMapper.countByParentId(dept.getId()) > 0 ) {
            throw new ParamException("当前部门下有子部门，无法删除");
        }
        // 子部门不存在，需要判断其下有无用户
        if (sysUserMapper.countBydeptId(dept.getId()) > 0) {
            throw new ParamException("当前部门下存在用户，无法删除");
        }
        sysDeptMapper.deleteByPrimaryKey(deptId);
    }
}
